package microcredit.db;

import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;

import microcredit.DatabaseUtilities;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ddlutils.Platform;

public class ImportExportDefault implements IImportExport{

	private static final Log LOGGER = LogFactory.getLog(ImportExportDefault.class);	
	private Platform p;
	private Connection conn;
		
	private boolean deleteDirectory(File path) {
		if( path.exists() ) {
			File[] files = path.listFiles();
			for(int i=0; i<files.length; i++) {
				if(files[i].isDirectory()) {
					deleteDirectory(files[i]);
				}
				else {
					files[i].delete();
				}
			}
		}
		return( path.delete() );
	}
	
	@Override
	public void importDatabase(File importfile) throws Exception {
		if (true) {
			importDatabaseRestore(importfile);
		}
//		else {
//			importDatabaseUnzip(importfile);
//		}
	}
	
	private void importDatabaseUnzip(File importfile) throws Exception {
		File tmpFolder = new File("tmp/import");
		String dbName;
		try {
			tmpFolder.mkdirs();			
			DatabaseUtilities.getInstance().unzipFolder(importfile, tmpFolder);
			if (tmpFolder.list().length > 0) {
				dbName = tmpFolder.list()[0];
				if (!new File("db/" + dbName).exists()) {
					throw new Exception("Database name in import file differs from local database");
				} else {
					File dbFolder = new File("db/"+dbName);
					deleteDirectory(dbFolder);
					dbFolder.mkdirs();
					DatabaseUtilities.getInstance().unzipFolder(importfile, dbFolder.getParentFile());
				}
			}
		} finally {
//			Factory.initFactoryNew();
			deleteDirectory(tmpFolder);
		}
	}
	
	private void importDatabaseRestore(File importfile) throws Exception {
		File tmpFolder = new File("tmp/import");
		try {
			tmpFolder.mkdirs();			
			DatabaseUtilities.getInstance().unzipFolder(importfile, tmpFolder);
			Connection c = Factory.createRestoreConnection(tmpFolder);
			c.close();
		} finally {
			deleteDirectory(tmpFolder);
		}
	}
	
	
	@Override
	public void exportDatabase(File targetFile) throws Exception {
		open();
		File tmpFolder = new File("./tmp/export");
		try {
			tmpFolder.mkdirs();
			exportIntoFolder(tmpFolder);
			DatabaseUtilities.getInstance().zipFolder(tmpFolder, targetFile);
		}  finally {
			conn.rollback();
			conn.close();
			deleteDirectory(tmpFolder);
		}
	}
	
	private void exportIntoFolder(File folder) throws Exception {
		PreparedStatement ps= conn.prepareStatement(
    		"CALL SYSCS_UTIL.SYSCS_BACKUP_DATABASE  (?)");
		ps.setString(1, folder.getAbsolutePath());
		ps.execute();
		ps.close();
	}
	
	private void open() throws Exception {
		p = Factory.createDefaultPlatform();
		conn = p.getDataSource().getConnection();
	}
	
	public static void main(String[] args) throws Exception {
		Factory.initFactoryNew();
		Factory.close(true);
		
		ImportExportDefault importExport = new ImportExportDefault();
		File f = new File("./asdf.zip");
//		importExport.exportDatabase(f);
		importExport.importDatabase(f);
		
		System.out.println(Factory.readVersion(Factory.createDefaultConnection()));
	}
}
